<!DOCTYPE HTML>
<html xmlns:v-bind="http://www.w3.org/1999/xhtml" xmlns:v-on="http://www.w3.org/1999/xhtml">

<head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>聊天室</title>
    <script src="./js/jquery.min.js"></script>
    <script src="./js/canvi.js"></script>
    <script src="./js/layui.all.js"></script>
    <!-- <link rel="stylesheet" type="text/css" href="./css/demo.css" /> -->
    <!-- <link rel="stylesheet" type="text/css" href="./css/normalize.css" /> -->
    <link rel="stylesheet" type="text/css" href="./css/canvi.css" />
    <link rel="stylesheet" type="text/css" href="./css/login.css" />
    <link rel="stylesheet" type="text/css" href="./css/layui.css" />
    <!--the css for jquery.mCustomScrollbar-->
    <link rel="stylesheet" href="./css/jquery.mCustomScrollbar.min.css" />
    <!--the css for this plugin-->
<!--    <link rel="stylesheet" href="./css/jquery.emoji.css" />-->
    <!--(Optional) the js for jquery.mCustomScrollbar's addon-->
    <script src="./js/jquery.mousewheel-3.0.6.min.js"></script>
    <!--the js for jquery.mCustomScrollbar-->
    <script src="./js/jquery.mCustomScrollbar.min.js"></script>
    <!--the js for this plugin-->
<!--    <script src="./js/jquery.emoji.js"></script>-->
    <!--vue-->
    <script src="./js/vue.min.js"></script>
    <!--引入变量-->
    <script src="./js/common.variate.js"></script>
    <link rel="stylesheet" type="text/css" href="./css/csshake.min.css">

</head>

<body onload="checkNotification()" style="background-color: rgb(230, 230, 230);font-size: 15px;font-weight:200;margin: 0px;padding: 0px;width: 100%">
    <aside id="aside" class="myCanvasNav canvi-navbar" data-position="left" data-push-content="false" style="width: 100vw;" inert="" aria-hidden="true">
        <div id="canvi" class="canvi-user-info" style="padding-top: 20px;padding-bottom: 20px;">
            <div class="canvi-user-info__data">
                <span id="activeRoom" class="canvi-user-info__title">房间号:</span>
                <a id="activeUser" class="canvi-user-info__meta">开心畅聊每一天😘</a><br>
                <a id="activePwd" class="canvi-user-info__meta"></a>
            </div>
            <div v-bind:title="msgSwitchTips" class="canvi-user-info__close" onclick="silence()">
                <img id="mute" src="./icon/unmute.png" style="width: 25px;">
            </div>
        </div>
        <ul id="cebian" class="canvi-navigation">
        </ul>
    </aside>

    <main class="js-canvi-content canvi-content"></main>

    <div>
        <button id="btn" style="display: none">查看在线人数</button>
        <div style="display: none;">
            <div>
                <span>昵称：</span>
                <input id="nick" type="text">
            </div>
            <div>
                <span>房间：</span>
                <input id="room" type="text">
            </div>
            <div>
                <span>用户ID：</span>
                <input id="userId" type="text">
            </div>
            <div class="login-input">
                <label>昵称：</label>
                <input type="text" placeholder="请输入昵称" id="nickname" class="list-input" />
            </div>
            <div class="login-input">
                <label>图片：</label>
                <input type="text" placeholder="请输入图片" id="image" class="list-input" />
            </div>

            <div class="login-input">
                <label>房间：</label>
                <input type="text" placeholder="请输入房间" onfocus="allRoom(this)" id="roomname" class="list-input" list="rooms" />
                <datalist id="rooms"></datalist>
            </div>
            <div class="login-input" style="height: 0px">
                <label>密码：</label>
                <input type="password" placeholder="密码可留空" id="password" class="list-input" list="rooms" />
            </div>
            <div class="login-input">
                <label>用户微信id：</label>
                <input type="text" placeholder="请输入用户微信id" id="weixinId" class="list-input" />
            </div>
        </div>

        <div id="message" style="display: none"></div>

        <div id="footer" class="footer">
            <div id="text" contenteditable="true"></div>
<!--            <div id="text"></div>-->
            <div id="toolbar">
                <!-- <img id="emoji" v-bind:title="emojiTips" src="icon/emoji.png" style="width: 26px;margin-left: 10px">
                <img id="sendImg" v-bind:title="pictureTips" onclick="moniSendImg()" src="icon/picture.png" style="width: 23px;margin-left: 10px">
                <img id="shakeMsg" v-bind:title="shakeTips" class="shake-constant shake-constant--hover" onclick="beginShake()" src="icon/shakeFalse.png" style="width: 22px;margin-left: 10px">
                <img id="clear" v-bind:title="clearTips" onclick="emptyScreen()" src="icon/clear.png" style="width: 23px;margin-left: 10px"> -->
                <span onclick="send()">发送</span>
                <!-- <img id="send" v-bind:title="sendTips" onclick="send()" src="icon/send.png" style="width: 24px;position: absolute;right: 10px"> -->
            </div>
        </div>

        <form id="imageUp" style="display: none">
            <a href='javascript:void(0);' class="blueButton">发图</a>
<!--            <input type="file" class="myFileUpload" name="file" id="image" onchange="sendImg(this)" />-->
        </form>
    </div>

    <!--    <div class="login" id="window">-->
    <!--        <div class="login-title">进入房间</div>-->
    <!--        <div class="login-input-content">-->

    <!--        </div>-->
    <!--        <div class="login-button" onclick="editNick()"><a style="text-decoration:none;color:#ffffff;" href="javascript:void(0);" id="login-button-submit">进入</a></div>-->
    <!--    </div>-->

</body>

<script type="text/javascript">
    // var domainName = "http://192.168.0.106:8091";
    // var webspcketHost = "ws://192.168.0.106:8091/websocket";
    // var domainName = "http://192.168.0.5:8091";
    // var webspcketHost = "ws://192.168.0.5:8091/websocket";

    // var domainName = "http://192.168.0.136:8091";
    // var webspcketHost = "ws://192.168.0.136:8091/websocket";
    // var imgUrl = "http://admin.ballnicethis.xyz/prod-api";
    // var imgUrl = "http://10.10.10.16/dev-api/";
    //正式服务器地址
    var domainName = "http://ballnicethis.xyz/";
    var webspcketHost = "ws://101.33.45.57:8091/websocket";
    var imgUrl = "http://admin.ballnicethis.xyz/prod-api";


    let  pageNum= 1;
    let  pageSize= 10;



    function GetQueryString(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return (r[2]);
        return null;
    }
    var url = window.location.href; //得到页面的url
    var URL_decode = decodeURI(decodeURI(url)); //对含有中文的url进行解码,注意是两次解码
    //自定义获取URL中某一参数的封装函数
    function GetQueryString_new(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = URL_decode.substr(1).match(reg); //注意这里使用的是解码之后的URL_decode
        if (r != null) {
            return unescape(r[2]); //2017年12月11日--注意：这里有个解密的操作。
        } else {
            return null;
        }
    }
    function first() {
        var room = GetQueryString("room");
        var weixinId = GetQueryString_new("weixinId");
        var nick = GetQueryString_new("nick");
        var image = GetQueryString_new("image");
        $("#roomname").val(room);
        $("#weixinId").val(weixinId);
        $("#nickname").val(nick);
        $("#image").val(image);
    }


    window.onload = function() {
        // getInitRoomAndUser();
        setTimeout(function() {
            first();
        }, 500);
        setTimeout(function() {
            editNick();
        }, 500);
        setTimeout(function() {
            getAllMsg();
        }, 500);
        setTimeout(function() {
            scrollToEnd2(pageNum,pageSize);
        }, 1500);
    };


    function scrollToEnd2() {
        var h = $("html,body").height() - $(window).height() + 60;
        $("html,body").animate({
            scrollTop: h
        }, 0);


    }
    function getPreAllMsg(){
        let roomname = $("#roomname").val();
        let weixinId = $("#weixinId").val();
        $.ajax({
            type: "POST",
            url: domainName + "/ws/getAllMessage",
            data: {
                room: roomname,
                pageNum: pageNum,
                pageSize: pageSize
            },
            dataType: "json",
            success: function(data) {
                let records = data.records;
                let h=$(document).height();
                console.log("高度:"+h)
                for (let i = 0; i < records.length; i++) {
                    let wexinName = records[i].wexinName;
                    let msg = records[i].msg;
                    var image=records[i].image;
                    if (records[i].wexinId == weixinId) {
                        if (records[i].type == 1) {
                            setPreMessageInnerHTML2(wexinName, msg, "",image);
                        } else {
                            setPreImgInnerHTML2(wexinName, msg);
                        }
                    } else {
                        if (records[i].type == 1) {
                            setPreMessageInnerHTML(wexinName, msg, "",image,wexinName);
                        } else {
                            setPreImgInnerHTML(wexinName, msg);
                        }
                    }
                }
                let endH=$(document).height()-h;
                $("html,body").animate({
                    scrollTop:endH+60
                }, 0);
                return data;
            }
        })
    }

    function getAllMsg() {
        let roomname = $("#roomname").val();
        let weixinId = $("#weixinId").val();
        $.ajax({
            type: "POST",
            url: domainName + "/ws/getAllMessage",
            data: {
                room: roomname,
                pageNum: pageNum,
                pageSize: pageSize
            },
            dataType: "json",
            success: function(data) {
                let records = data.records.reverse();
                for (let i = 0; i < records.length; i++) {
                    let wexinName = records[i].wexinName;
                    let msg = records[i].msg;
                    var image=records[i].image;
                    if (records[i].wexinId == weixinId) {
                        if (records[i].type == 1) {
                            setMessageInnerHTML2(wexinName, msg, "",image);
                        } else {
                            setImgInnerHTML2(wexinName, msg);
                        }
                    } else {
                        if (records[i].type == 1) {
                            setMessageInnerHTML(wexinName, msg, "",image,wexinName);
                        } else {
                            setImgInnerHTML(wexinName, msg);
                        }
                    }
                }
                return data;
            }
        })
    }
    window.onfocus = function() {
        focus = false;
    };
    window.onblur = function() {
        focus = true;
    };

    // for IE
    document.onfocusin = function() {
        focus = false;
    };
    document.onfocusout = function() {
        focus = true;
    };
    //判断当前浏览器是否支持WebSocket
    if ('WebSocket' in window) {
        websocket = new WebSocket(webspcketHost);
    } else {
        layer.msg(unSupportWsMsg, {
            anim: 6
        })
    }

    //连接发生错误的回调方法
    websocket.onerror = function() {
        layer.msg(onerrorMsg, {
            anim: 6
        });
    };

    //连接成功建立的回调方法
    websocket.onopen = function(event) {
        self.setInterval("ping()", 55000);
    }

    // 鼠标悬停在某些按钮上时延迟Tips
    function delayTips(tips, obj, style, time) {
        timer = setTimeout(messagebox, time == null ? 700 : time, tips, obj, style)
    }

    // 停止延迟Tips的计时器
    function stopTimer() {
        if (timer != null) {
            clearTimeout(timer);
            layer.closeAll('tips');
        }
    }

    // Tips
    function messagebox(tips, obj, style) {
        layer.tips(tips, obj, style);
    }

    //接收到消息的回调方法
    websocket.onmessage = function(event) {
        var data = JSON.parse(event.data)
        var msg = data.msg;
        var nick = data.sendUser;
        var shakeStatus = data.shake;
        var image=data.image;
        var state=data.state;
        // if (focus && mute%2==0) {
        //     playSound();
        //     notifyMe(data);
        // }
        switch (data.type) {
            case 'init':
                getOnlion(document.getElementById('room').value);
                layer.msg(msg);
                break;
            case 'msg':
                setMessageInnerHTML(nick, text2Emoji2(msg), shakeStatus,image,state);
                break;
            case 'img':
                setImgInnerHTML(nick, msg);
                break;
            // case 'bing':
            //     document.getElementById('userId').value = data.id;
            //     $('body').css("background-image","url("+msg+")");
            //     break;
            default:
                break;
        }
    }

    //连接关闭的回调方法
    websocket.onclose = function() {
        layer.alert(oncloseMsg, {
            icon: 2
        });
        $("#footer").animate({
            bottom: '-200px'
        }, 400);

    }

    //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
    window.onbeforeunload = function() {
        websocket.close();
    }

    // 清空屏幕
    function emptyScreen() {
        layer.msg('是否清空屏幕？', {
            anim: 6,
            time: 0 //不自动关闭
            ,
            btn: ['确定', '取消'],
            yes: function(index) {
                layer.close(index);
                $("#message").empty();
            }
        });
    }

    // 让某个消息停止抖动
    function stopShake(obj) {
        var array = $(obj).attr("class").split(" ")
        $(obj).removeClass(array[3]);
    }

    // 查看原图
    function originalImage(obj) {
        layer.photos({
            photos: obj,
            anim: 5 //0-6的选择，指定弹出图片动画类型，默认随机（请注意，3.0之前的版本用shift参数）
        });
    }

    //将消息显示在网页上
    function setMessageInnerHTML(nick, msg, shake,image,state) {
        if (state!="机器人"){
            var a = '<div class="botui-message-left"><div ondblclick="stopShake(this)" style="margin-left: 10px"  class="botui-message-content shake-constant shake-constant--hover';
            if (shake != null || shake != "") {
                a = a + ' ' + shake + '">';
            } else {
                a = a + '">';
            }
            if (image!=undefined && image!=null && image!=''){
                $("#message").append("<div class='sendUser'><b style='margin-left: 10px;font-size: 10px;color: #00000080'>" + nick + "</b><b style='float: left;'><img style='width: 45px!important;height: 45px!important;' src='"+ imgUrl+image +"' /></b></div>" + a + msg + b);
            }else{
                $("#message").append("<div class='sendUser'><b  style='margin-left: 10px;font-size: 10px;color: #00000080'>" + nick + "</b><b style='float: left;'><img style='width: 45px!important;height: 45px!important;' src='icon/root.png' /></b></div>" + a + msg + b);
            }
            scrollToEnd();
            $(".botui-message-content").animate({
                'margin-left': '10px'
            }, 200);
        }else{
            var a = '<div class="botui-message-left"><div ondblclick="stopShake(this)" style="margin-left: 10px"  class="botui-message-content shake-constant shake-constant--hover';
            if (shake != null || shake != "") {
                a = a + ' ' + shake + '">';
            } else {
                a = a + '">';
            }

            $("#message").append("<div class='sendUser' ><b  style='margin-left: 10px;font-size: 10px;color: red'>" + nick + "</b><b style='float: left;'><img style='width: 45px!important;height: 45px!important;' src='icon/root.png' /></b></div>" + a + msg + b);

            scrollToEnd();
            $(".botui-message-content").animate({
                'margin-left': '10px'
            }, 200);
        }



    }

    //将消息显示在网页上
    function setPreMessageInnerHTML(nick, msg, shake,image,state) {
        if (state!="机器人"){
            var a = '<div class="botui-message-left"><div ondblclick="stopShake(this)" style="margin-left: 10px"  class="botui-message-content shake-constant shake-constant--hover';
            if (shake != null || shake != "") {
                a = a + ' ' + shake + '">';
            } else {
                a = a + '">';
            }
            if (image!=undefined && image!=null && image!=''){
                $("#message").prepend("<div class='sendUser'><b style='margin-left: 10px;font-size: 10px;color: #00000080'>" + nick + "</b><b style='float: left;'><img style='width: 45px!important;height: 45px!important;' src='"+ imgUrl+image +"' /></b></div>" + a + msg + b);
            }else{
                $("#message").prepend("<div class='sendUser'><b  style='margin-left: 10px;font-size: 10px;color: #00000080'>" + nick + "</b><b style='float: left;'><img style='width: 45px!important;height: 45px!important;' src='icon/root.png' /></b></div>" + a + msg + b);
            }
            // scrollToEnd();
            $(".botui-message-content").animate({
                'margin-left': '10px'
            }, 200);
        }else{
            var a = '<div class="botui-message-left"><div ondblclick="stopShake(this)" style="margin-left: 10px"  class="botui-message-content shake-constant shake-constant--hover';
            if (shake != null || shake != "") {
                a = a + ' ' + shake + '">';
            } else {
                a = a + '">';
            }

            $("#message").prepend("<div class='sendUser' ><b  style='margin-left: 10px;font-size: 10px;color: red'>" + nick + "</b><b style='float: left;'><img style='width: 45px!important;height: 45px!important;' src='icon/root.png' /></b></div>" + a + msg + b);

            // scrollToEnd();
            $(".botui-message-content").animate({
                'margin-left': '10px'
            }, 200);
        }



    }

    //将自己发的消息显示在网页上
    function setPreMessageInnerHTML2(nick, msg, shake,image) {
        var c = '<div class="botui-message-right"><div ondblclick="stopShake(this)" class="botui-message-content2 shake-constant shake-constant--hover';
        if (shake != null || shake != "") {
            c = c + ' ' + shake + '">';
        } else {
            c = c + '">';
        }
        if (image!=undefined && image!=null && image!=''){

            $("#message").prepend("<div class='sendUser' style='text-align: right;'><b style='margin-right: 10px;font-size: 10px;color: #00000080'>" + nick + "</b><b style='float: right;'><img style='width: 45px!important;height: 45px!important;' src='"+imgUrl+image+"' /></b></div>"
                + c + msg + b);
        }else{
            $("#message").prepend("<div class='sendUser' style='text-align: right;'><b style='margin-right: 10px;font-size: 10px;color: #00000080'>" + nick + "</b><b style='float: right;'><img style='width: 45px!important;height: 45px!important;' src='icon/default.png' /></b></div>"
                + c + msg + b);
        }
        // $("#message").append("<div class='sendUser' style='text-align: right;'><b>" + nick + "</b></div>" + c + msg + b);
        // scrollToEnd();
        scrollToEnd2();
        $(".botui-message-content2").animate({
            'margin-right': '10px'
        }, 200);
    }


    //将自己发的消息显示在网页上
    function setMessageInnerHTML2(nick, msg, shake,image) {
        var c = '<div class="botui-message-right"><div ondblclick="stopShake(this)" class="botui-message-content2 shake-constant shake-constant--hover';
        if (shake != null || shake != "") {
            c = c + ' ' + shake + '">';
        } else {
            c = c + '">';
        }
        if (image!=undefined && image!=null && image!=''){

            $("#message").append("<div class='sendUser' style='text-align: right;'><b style='margin-right: 10px;font-size: 10px;color: #00000080'>" + nick + "</b><b style='float: right;'><img style='width: 45px!important;height: 45px!important;' src='"+imgUrl+image+"' /></b></div>"
                + c + msg + b);
        }else{
            $("#message").append("<div class='sendUser' style='text-align: right;'><b style='margin-right: 10px;font-size: 10px;color: #00000080'>" + nick + "</b><b style='float: right;'><img style='width: 45px!important;height: 45px!important;' src='icon/default.png' /></b></div>"
                + c + msg + b);
        }
        // $("#message").append("<div class='sendUser' style='text-align: right;'><b>" + nick + "</b></div>" + c + msg + b);
        // scrollToEnd();
        scrollToEnd2();
        $(".botui-message-content2").animate({
            'margin-right': '10px'
        }, 200);
    }

    //将图片显示在网页上
    function setImgInnerHTML(nick, msg) {
        $("#message").append("<div class='sendUser'><b  style='margin-left: 10px;font-size: 10px;color: red'>" + nick + "</b><b style='float: left;'><img style='width: 45px!important;height: 45px!important;' src='icon/root.png' /></b></div>" + aa + "<img style=\"width: 300px;\" src='" + msg + "'" + b);
        scrollToEnd();
        $(".botui-message-content-img").animate({
            'margin-left': '-10px'
        }, 200);
    }

    //将图片显示在网页上
    function setPreImgInnerHTML(nick, msg) {
        $("#message").prepend("<div class='sendUser'><b  style='margin-left: 10px;font-size: 10px;color: red'>" + nick + "</b><b style='float: left;'><img style='width: 45px!important;height: 45px!important;' src='icon/root.png' /></b></div>" + aa + "<img style=\"width: 300px;\" src='" + msg + "'" + b);
        scrollToEnd();
        $(".botui-message-content-img").animate({
            'margin-left': '-10px'
        }, 200);
    }

    //将自己发的图片显示在网页上
    function setImgInnerHTML2(nick, msg) {
        $("#message").append("<div class='sendUser' style='text-align: right;font-size: 10px;color: #00000080'><b>" + nick + "</b></div>" + cc + "<img style=\"width: 300px;\" src='" + msg + "'" + b);
        // scrollToEnd();
        scrollToEnd2();
        $(".botui-message-content2-img").animate({
            'margin-right': '0px'
        }, 200);
    }
    //将自己发的图片显示在网页上
    function setPreImgInnerHTML2(nick, msg) {
        $("#message").prepend("<div class='sendUser' style='text-align: right;font-size: 10px;color: #00000080'><b>" + nick + "</b></div>" + cc + "<img style=\"width: 300px;\" src='" + msg + "'" + b);
        // scrollToEnd();
        scrollToEnd2();
        $(".botui-message-content2-img").animate({
            'margin-right': '0px'
        }, 200);
    }

    function moniSendImg() {
        document.getElementById("image").click();
    }

    //关闭连接
    function closeWebSocket() {
        websocket.close();
    }

    //开关抖动消息
    function beginShake() {
        if (shakeNum == 8) {
            $('#shakeMsg').attr("src", "./icon/shakeFalse.png");
            $("#shakeMsg").removeClass(shakeList[shakeNum]);
            layer.msg("抖动消息已关闭");
            shakeNum = 0;
        } else {
            $("#shakeMsg").removeClass(shakeList[shakeNum]);
            shakeNum += 1;
            $('#shakeMsg').attr("src", "./icon/shakeTrue.png");
            $("#shakeMsg").addClass(shakeList[shakeNum]);
            layer.msg(shakeChinese[shakeNum]);
        }
    }

    //发送消息
    function send() {
        var msgBak = document.getElementById('text').innerHTML;
        var nick = $("#nick").val();
        var image = $("#image").val();
        // 转换emoji
        // $($("#text").children(".emoji_icon")).each(function() {
        //     $(this).prop('outerHTML', textHead + $(this).attr("src").split(emojiPath)[1] + textFoot);
        // });
        var msg = document.getElementById('text').innerText;
        if (msg != null && msg != "") {
            msg = msg.replace(/"/g, "'");
            var map = new Map();
            map.set("type", "msg");
            map.set("msg", msg);
            var shiels = new Array();
            shieldMap.forEach(function(value) {
                shiels.push(value);
            })
            map.set("shiels", shiels);
            map.set("shake", shakeList[shakeNum]);
            var map2json = Map2Json(map);
            if (map2json.length < 8000) {
                websocket.send(map2json);
                document.getElementById('text').innerHTML = null;
                setMessageInnerHTML2(nick, msg, shakeList[shakeNum],image);
            } else {
                $("#text").html(msgBak);
                layer.msg("文本太长了，少写一点吧😭", {
                    anim: 6
                });
            }
        } else {
            layer.msg("发空消息是什么意思呢？🤔", {
                anim: 6
            });
        }
    }

    //服务端如果用nginx做转发,可能会因'proxy_read_timeout'配置的过短而自动断开连接,默认是一分钟,所以发送心跳连接,保证不聊天的状态下不会断开
    function ping() {
        var map = new Map();
        map.set("type", "ping");
        var map2json = Map2Json(map);
        websocket.send(map2json);
    }

    // 将文本转换回emoji图片
    function text2Emoji2(emojiMsg) {
        return emojiMsg.replace(new RegExp(textHead, "g"), emojiHead).replace(new RegExp(textFoot, "g"), emojiFoot);
    }

    //发送昵称和房间号
    function sendnick(nick, room, pwd, weixinId) {
        var map = new Map();
        map.set("type", "init");
        map.set("nick", nick);
        map.set("room", room);
        map.set("pwd", pwd);
        map.set("weixinId", weixinId);

        var message = Map2Json(map);
        websocket.send(message);
        document.getElementById('text').innerHTML = null;
        document.getElementById('activeRoom').innerText = '房间：' + room;
        document.getElementById('activeUser').innerText = '昵称：' + nick;
        if (pwd != null && pwd != "") {
            document.getElementById('activePwd').innerText = '密码：' + pwd;
        } else {
            $("#activePwd").css('display', 'none');
        }
        $('#btn').trigger("click");
        getOnlion(document.getElementById('room').value);
        $('body').css("background-image", "none");
        $("#window").animate({
            top: '-100%'
        }, 500);
        $("#footer").animate({
            bottom: '0px'
        }, 400);
        $("#message").show();
        // layer.alert(firstTips);
        //因为该方法会引起较近的动画卡顿，所以让他先老实一会儿
        // setTimeout(function() {
        //     loadEmoji();
        // }, 500);
    }

    // 加载表情，这个方法需要一定时间，因此可能造成肉眼可见的卡顿
    // function loadEmoji() {
    //     $("#text").emoji({
    //         button: "#emoji",
    //         showTab: true,
    //         animation: 'slide',
    //         icons: [{
    //             name: "QQ表情",
    //             path: "dist/img/qq/",
    //             maxNum: 154,
    //             file: ".gif"
    //
    //         }, {
    //             name: "贴吧表情",
    //             path: "dist/img/tieba/",
    //             maxNum: 50,
    //             file: ".jpg"
    //         }, {
    //             name: "dog",
    //             path: "dist/img/dog/",
    //             maxNum: 37,
    //             file: ".png"
    //         }, {
    //             name: "坏坏",
    //             path: "dist/img/huai/",
    //             maxNum: 189,
    //             file: ".png"
    //         }, {
    //             name: "坏坏GIF",
    //             path: "dist/img/huaiGif/",
    //             maxNum: 26,
    //             file: ".gif"
    //         }, {
    //             name: "微博",
    //             path: "dist/img/weibo/",
    //             maxNum: 93,
    //             file: ".png"
    //         }, {
    //             name: "猥琐萌",
    //             path: "dist/img/xiaoren/",
    //             maxNum: 186,
    //             file: ".gif"
    //         }]
    //     });
    // }

    //监听按键
    $(document).keydown(function(e) {
        // 回车键发送消息
        if (e.keyCode == 13) {
            var topValue = $("#window").css('top');
            var topPx = topValue.substring(0, topValue.length - 2);
            if (topPx > 0) {
                editNick();
            } else {
                send();
                return false;
            }
        } else if (e.keyCode == 27) { //Esc键关闭抖动消息
            $('#shakeMsg').attr("src", "./icon/shakeFalse.png");
            $("#shakeMsg").removeClass(shakeList[shakeNum]);
            shakeNum = 0;
            layer.msg("抖动消息已关闭");
        }
    });

    //发送消息后自动滚到底部
    // function scrollToEnd() {
    //     var h = $("html,body").height() - $(window).height() + 60;
    //     $("html,body").animate({
    //         scrollTop: h
    //     }, 0);
    // }

    $(window).scroll(function () {
        if (($(window).scrollTop()) == 0) {
            console.log(pageNum)
            //当底部基本距离+滚动的高度〉=文档的高度-窗体的高度时；
            //我们需要去异步加载数据了
            pageNum=pageNum+1;
            getPreAllMsg();
        }
    });

    //发送消息后自动滚到底部
    function scrollToEnd() {
        var h = $("html,body").height() - $(window).height() + 60;
        var scrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;
        let juli= document.documentElement.scrollHeight - scrollTop - document.documentElement.clientHeight;

        if( juli > 900){
        }else {
            $("html,body").animate({
                scrollTop: h
            }, 0);
        }


    }



    function getInitRoomAndUser() {
        $.ajax({
            type: "POST",
            url: domainName + "/ws/getInitUser",
            // data: {room:roomname,nick:nickname,pwd:password},
            dataType: "json",
            success: function(data) {
                $("#nickname").val(data.nick);
                $("#roomname").val(data.room);
                $("#weixinId").val(data.weixinId);

                return data;
            }
        })
    }

    //设置房间号和昵称并发送，再模拟‘#btn’的点击事件，以弹出侧边栏
    function editNick() {
        var nickname = $("#nickname").val();
        var roomname = $("#roomname").val();
        var weixinId = $("#weixinId").val();
        var password = $("#password").val();
        document.getElementById('nick').value = nickname;
        document.getElementById('room').value = roomname;
        if (nickname == "" || roomname == "" || weixinId == "") {
            layer.msg("房间号和昵称不能为空！", {
                anim: 6
            });
            return;
        }
        $.ajax({
            type: "POST",
            url: domainName + "/ws/judgeNick",
            data: {
                room: roomname,
                nick: nickname,
                pwd: password,
                weixinId: weixinId
            },
            dataType: "json",
            success: function(data) {
                //房间存在但是昵称重复
                if (data.code == 1) {
                    layer.msg(data.msg, {
                        anim: 6
                    });
                    document.getElementById('nickname').value = '';
                    return;
                } else if (data.code == 2) { //房间存在但是密码错误
                    if (password == null || password == "") {
                        if ($(".login").css("height") == "300px") {
                            layer.msg("请输入密码", {
                                anim: 6
                            });
                        } else {
                            ejectPwd("该房间需要密码");
                        }
                    } else {
                        layer.msg(data.msg, {
                            anim: 6
                        });
                        document.getElementById('password').value = "";
                    }
                    return;
                } else if (data.code == 0) {
                    //表示房间不存在
                    if (password == null || password == "") {
                        // layer.confirm('需要为该房间添加一个密码吗？', {
                        //     btn: ['需要','不用'] //按钮
                        // }, function(){
                        //     ejectPwd("请输入一个密码");
                        //     layer.closeAll('dialog');
                        // }, function(){
                        sendnick(nickname, roomname, password, weixinId);
                        // });
                    } else {
                        sendnick(nickname, roomname, password, weixinId);
                    }
                } else {
                    sendnick(nickname, roomname, password, weixinId);
                }
            }
        });
    }


    //获得当前房间中的所有用户
    function getOnlion(room) {
        $.ajax({
            type: "POST",
            url: domainName + "/ws/online",
            data: {
                room: room
            },
            dataType: "json",
            success: function(data) {
                if (data.onlineNum > 0) {
                    var onlineUsera = data.onlineUsera;
                    $("#cebian").html("");
                    onlineUsera.forEach(function(user) {
                        var color = "#00ce46";
                        if (shieldMap.has("user-" + user.id)) {
                            color = "#FF3A43"
                        }
                        if (user.id != $("#userId").val()) {
                            var html = '<li>\n' +
                                '                <a class="canvi-navigation__item">\n' +
                                '                    <span title="点击屏蔽此人，不让其接收自己的消息" id="user-' + user.id + '" class="canvi-navigation__icon-wrapper" onclick="shield(this)" style="background: ' + color + ';">\n' +
                                '                        <span class="canvi-navigation__icon icon-iconmonstr-code-13"></span>\n' +
                                '                    </span>\n' +
                                '                    <span class="canvi-navigation__text">' + user.nick + '</span>\n' +
                                '                </a>\n' +
                                '            </li>';
                            $("#cebian").append(html);
                        }
                    });
                }
            }
        });
    }

    // 屏蔽某个成员不让他接收我的消息
    function shield(obj) {
        var userId = obj.id.substring(5)
        if (userId != $("#userId").val()) {
            if (shieldMap.has(obj.id)) {
                shieldMap.delete(obj.id);
                layer.msg('该用户将会重新接收到您的消息😁');
            } else {
                shieldMap.set(obj.id, userId);
                layer.msg('该用户将不会接收到您的消息了😉');
            }
            getOnlion(document.getElementById('room').value);
        } else {
            layer.msg('这个是您自己呦，点了也没用😂');
        }
    }

    //播放提示音
    function playSound() {
        var borswer = window.navigator.userAgent.toLowerCase();
        if (borswer.indexOf("ie") >= 0) {
            //IE内核浏览器
            var strEmbed = '<embed name="embedPlay" src="../../../resources/static/audio/ding.mp3" autostart="true" hidden="true" loop="false"></embed>';
            if ($("body").find("embed").length <= 0)
                $("body").append(strEmbed);
            var embed = document.embedPlay;

            //浏览器不支持 audion，则使用 embed 播放
            embed.volume = 100;
            //embed.play();
        } else {
            //非IE内核浏览器
            var strAudio = "<audio id='audioPlay' src='../../../resources/static/audio/ding.mp3' hidden='true'>";
            if ($("body").find("audio").length <= 0)
                $("body").append(strAudio);
            var audio = document.getElementById("audioPlay");

            //浏览器支持 audion
            audio.play();
        }
    }


    var t = new Canvi({
        content: ".js-canvi-content",
        isDebug: !1,
        navbar: ".myCanvasNav",
        openButton: ".js-canvi-open-button--left",
        position: "left",
        pushContent: !1,
        speed: "0.2s",
        width: "100vw",
        responsiveWidths: [
            //     {
            //     breakpoint: "600px",
            //     width: "21%"
            // }
            // {
            //     breakpoint: "1280px",
            //     width: "21%"
            // }
            //     {
            //     breakpoint: "1600px",
            //     width: "21%"
            // }
        ]
    })


    function sendImg(obj) {
        var file = document.getElementById("imageUp");
        var image = document.getElementById("image");
        if (!(image.value == null || image.value == "")) {
            var img = getObjectURL(obj.files[0]);
            var nick = document.getElementById('weixinId').value;
            setImgInnerHTML2(nick, img);
            var form = new FormData(file);
            loadImage(image, 1024);
            upImgByLocalApi(form);
            // form.append("type","multipart");
            // loadImage(image,10240);
            // setTimeout(function(){ upImgByFigureBed(form); }, 300);
            image.value = null;
        }
    }

    function getObjectURL(file) {
        var url = null;
        if (window.createObjcectURL != undefined) {
            url = window.createOjcectURL(file);
        } else if (window.URL != undefined) {
            url = window.URL.createObjectURL(file);
        } else if (window.webkitURL != undefined) {
            url = window.webkitURL.createObjectURL(file);
        }
        return url;
    }

    //使用图床上传图片
    function upImgByFigureBed(form) {
        // var url;
        $.ajax({
            url: "http://api.yum6.cn/sinaimg.php",
            type: "POST",
            data: form,
            async: false,
            processData: false,
            contentType: false,
            success: function(data) {
                var url = data.url.replace("thumb150", "large");
                if (url != null && url != "") {
                    var map = new Map();
                    map.set("type", "img");
                    map.set("msg", url);
                    var shiels = new Array();
                    shieldMap.forEach(function(value) {
                        shiels.push(value);
                    })
                    map.set("shiels", shiels);
                    var map2json = Map2Json(map);
                    websocket.send(map2json);
                }
            },
            error: function(data) {
                layer.msg("失败", {
                    anim: 6
                });
            }
        });
    }

    //使用系统本身接口上传图片
    function upImgByLocalApi(form) {
        $.ajax({
            url: domainName + "/ws/fileUpload",
            type: "POST",
            data: form,
            async: false,
            processData: false,
            contentType: false,
            success: function(data) {
                var url = data.url;
                if (url != null && url != "") {
                    var map = new Map();
                    map.set("type", "img");
                    map.set("msg", url);
                    var shiels = new Array();
                    shieldMap.forEach(function(value) {
                        shiels.push(value);
                    })
                    map.set("shiels", shiels);
                    var map2json = Map2Json(map);
                    websocket.send(map2json);
                }
            },
            error: function(data) {
                layer.msg("失败", {
                    anim: 6
                });
            }
        });
    }

    function Map2Json(map) {
        var str = "{";
        map.forEach(function(value, key) {
            str += '"' + key + '"' + ':' + '"' + value + '",';
        })
        str = str.substring(0, str.length - 1)
        str += "}";
        return str;
    }

    //校验图片类型及大小
    function loadImage(img, size) {
        var filePath = img.value;
        var fileExt = filePath.substring(filePath.lastIndexOf("."))
            .toLowerCase();

        if (!checkFileExt(fileExt)) {
            layer.msg("您上传的文件不是图片,请重新上传！", {
                anim: 6
            });
            img.value = "";
            return;
        }
        if (img.files && img.files[0]) {
            if ((img.files[0].size / 1024).toFixed(0) > size) {
                layer.msg("图片不能超过1M,请重新选择", {
                    anim: 6
                });
                img.value = "";
                return;
            }
        } else {
            img.select();
            var url = document.selection.createRange().text;
            try {
                var fso = new ActiveXObject("Scripting.FileSystemObject");
            } catch (e) {
                layer.msg('如果你用的是ie8以下 请将安全级别调低！', {
                    anim: 6
                });
            }
            layer.msg("文件大小为：" + (fso.GetFile(url).size / 1024).toFixed(0) + "kb", {
                anim: 6
            });
        }
    }

    function checkFileExt(ext) {
        if (!ext.match(/.jpg|.jpeg|.gif|.png|.bmp/i)) {
            return false;
        }
        return true;
    }

    function notifyMe(data) {
        var notification = null;
        var msg = data.msg;
        var nick = data.sendUser;
        var type = data.type;
        switch (type) {
            case 'init':
                notification = new Notification(nick, {
                    body: msg,
                    icon: 'http://' + host + '/icon/enter.png',
                });
                break;
            case 'msg':
                notification = new Notification(nick, {
                    body: msg,
                    icon: 'http://' + host + '/icon/mail.png',
                });
                break;
            case 'img':
                notification = new Notification(nick, {
                    icon: msg,
                    // body: '你收到一张图片',
                });
                break;
            default:
                break;
        }

        // 先检查浏览器是否支持
        if (!("Notification" in window)) {
            layer.msg("您的浏览器不支持桌面通知", {
                anim: 6
            });
        }

        // 检查用户是否同意接受通知
        else if (Notification.permission === "granted") {
            // If it's okay let's create a notification
            var notification1 = notification;
            notification.onclick = function() {
                notification.close();
                window.resizeBy(-100, -100)
            };
        }

        // 否则我们需要向用户获取权限
        else if (Notification.permission !== 'denied') {
            Notification.requestPermission(function(permission) {
                // 如果用户同意，就可以向他们发送通知
                if (permission === "granted") {
                    var notification1 = notification;
                    notification.onclick = function() {
                        notification.close();
                        window.resizeBy(-100, -100)
                    };
                }
            });
        }
        // 最后，如果执行到这里，说明用户已经拒绝对相关通知进行授权
        // 出于尊重，我们不应该再打扰他们了
    }

    function checkNotification() {
        $(".login").animate({
            height: '250px'
        }, 1);
        $(".login-input-content").animate({
            'margin-top': '0px'
        }, 1);
        if (!("Notification" in window)) {
            layer.msg("您的浏览器不支持桌面通知", {
                anim: 6
            });
        } else {
            Notification.requestPermission();
        }
    }

    function allRoom(obj) {
        $.ajax({
            type: "POST",
            url: domainName + "/ws/allRoom",
            dataType: "json",
            success: function(data) {
                var rooms = data.rooms;
                $("#rooms").empty();
                if (rooms.length > 0) {
                    layer.tips("双击或点这里可选择已存在的房间", obj);
                }
                rooms.forEach(function(room) {
                    var html = '<option value="' + room + '">';
                    $("#rooms").append(html);
                });

            }
        });
    }

    function silence() {
        mute++;
        if (mute % 2 == 0) {
            $('#mute').attr("src", "./icon/unmute.png");
            layer.msg("消息通知已开启");
        } else {
            $('#mute').attr("src", "./icon/mute.png");
            layer.msg("消息通知已关闭");
        }
    }

    // 弹出密码框
    function ejectPwd(message) {
        $(".login-input").animate({
            height: '35px'
        }, 300);
        $(".login").animate({
            height: '300px'
        }, 300);
        $("#password").attr('placeholder', message);
    }

    new Vue({
        el: '#toolbar',
        data: {
            emojiTips: emojiTips,
            pictureTips: pictureTips,
            shakeTips: shakeTips,
            clearTips: clearTips,
            sendTips: sendTips,
        }
    })

    new Vue({
        el: '#canvi',
        data: {
            msgSwitchTips: msgSwitchTips
        }
    })
</script>

</html>